/*
* @author: yunyang
* @date: 2013/05/23
* @description: 分页控件
*/
(function ($, undefined) {
    //TODO：输入框BUG修复
    $.fn.paging = function (option) {
        var _this = this.eq(0);
        var __dataKey = "__class";
        var _data;
        // 缓存对象
        if (_this.data(__dataKey)) {
            return _this.data(__dataKey);
        }

		// 判断是否存在缓存对象
        if (typeof option == 'string') {
            if (option == 'exists') {
                return false;
            }
        } else if (option == null) {
            return false;
        }

        var Paging = function (option) {

            /*-----------------------------------------------参数---------------------------------------*/
            this.total = 0; //默认值
            this.pageSize = 10; //默认值
            this.currentPage = 1; //默认值
            this.pattern = '[<ncnn>]g'; //默认值
            this.firstPage = 1; //默认值
            this.preview = 1; //默认值
            this.next = 1; //默认值
            this.lastPage = 1; //默认值
            this.needTrigerEvent = true;
			//页面改变触发事件 可扩展
			this.pageChangeed = function(index){
				/**
					$.ajax(.....);//这里面只需要
				*/
			}

            /*-------------------------------------------私有方法-------------------------------------------*/
            this._setOption = function (option) {
                option = $.extend(this.option || $.fn.paging.option, option || {});
                this.option = option;
                return this;
            };
            this._constructor = function (option) {
                return this._setAttributes(option);
            };
            // 设置分页控件属性
            this._setAttributes = function (option) {
                this._setOption(option);
                this._setTotal(option.total);
                this._setPageSize(option.pageSize);
                this._setPattern(option.pattern);
                this._setFirstPage();
                this._setLastPage();
                this._setCurrentPageTemp(option.currentPage);
				this._setNeedTrigerEvent(option.needTrigerEvent);
                this.show();
                this.option = undefined;
                delete this.option;
                return this;
            };
            //设置总条目数 参数为空 默认为 0
            this._setTotal = function (total) {
                this.total = total || this.total;
                if (this.total < 0) {
                    this.total = 0;
                }
            };
            //设置页面大小 如果参数为空那么默认大小 10条记录每页
            this._setPageSize = function (pageSize) {
                this.pageSize = pageSize || this.pageSize;
                if (this.pageSize < 0) {
                    this.pageSize = 10;
                }
            };
            //设置当前页 参数为空 默认为 1
            this._setCurrentPage = function (index) {
                index = index || this.currentPage;
                index = this._vaildatePageIndex(index);
                this.currentPage = index;
                this.next = index + 1;
                this.preview = index - 1;
                if (index >= this.lastPage) {
                    this.currentPage = this.lastPage;
                    this.next = this.lastPage;
                }
                if (index <= this.firstPage) {
                    this.preview = this.firstPage;
                    this.currentPage = this.firstPage;
                }
                return this;
            };
			this._setCurrentPageTemp = function(index){
				index = index || this.currentPage;
				index = this._vaildatePageIndexTemp(index);
                this.currentPage = index;
                this.next = index + 1;
                this.preview = index - 1;
				return this;
			};
            //设置页面模式  默认为 [<ncnn>]
            this._setPattern = function (pattern) {
                this.pattern = pattern || this.pattern;
                //      this._formatPattern();
            };
            //设置首页 默认为 1 
            this._setFirstPage = function () {
                this.firstPage = 1;
            };
            //设置尾页
            this._setLastPage = function () {
                if (this.total < 0) {
                    this._setTotal(0);
                }
                var last = Math.ceil(this.total / this.pageSize);
                if (this.pageSize < 0) {
                    this._setPageSize();
                }
                last = last > 0 ? last : 1;
                this.lastPage = last;
            };
			this._setNeedTrigerEvent = function(flag){
				if(flag == undefined){
					return this;
				}
				if(flag == false){
					this.needTrigerEvent = false;
				}
				return this;
				
			}
            //获得页面模式类型
            this._getType = function (ch) {
                switch (ch) {
                    case "[": return "first";
                    case "<": return "preview";
                    case "n":
                    case "c": return "block";
                    case ">": return "next";
                    case "]": return "last";
                    case "g": return "goto";
                }
            };

            //显示分页控件框架 框架：包裹分页内容
            this._showPagingFramework = function () {
                if (this.total <= 0) {
                    return;
                }
                _this.append('<div class="jquery_paging"><div class="wapper paging-wapper"><div class="pager"><ul class="paging-content"></ul></div></div><div class="clear"></div></div>');
            }

            //显示分页控件内容
            this._showPagingContent = function () {
                if (this.total <= 0) {
                    return;
                }
                var pattern = '';
                for (var i = 0; i < this.pattern.length; i++) {
                    var item = this.pattern.charAt(i);
                    if (item === 'n' || item === 'c') {
                        pattern += item;
                    }
                }

                var length = pattern.length;
                var current = pattern.indexOf('c') + 1;
                var beforeCurrent = current - 1;
                var afterCurrent = length - current;
                var start = this.currentPage - beforeCurrent > 0 ? this.currentPage - beforeCurrent : 1;
                var end = this.currentPage + afterCurrent <= this.lastPage ? this.currentPage + afterCurrent : this.lastPage;
                if ((end + 1 - start) < 4) {
                    var val = start - (4 - (end + 1 - start));
                    start = val > 0 ? val : 1;
                }
                if ((end + 1 - start) < 4) {
                    var val = 4 - (end + 1 - start);
                    end = end + val;
                }
                if (end > this.lastPage) {
                    end = this.lastPage;
                }
                for (var i = this.pattern.length - 1; i >= 0; i--) {
                    var item = this.pattern.charAt(i);
                    if (item === 'n' || item === 'c') {
                        if (start <= end) {
                            this.value = end;
                            _this.find(".paging-content").append(this._getPagingContentItemHtml(this._getType(item)));
                            end--;
                        }
                    }
                    if (item === '[' || item === ']' || item === '<' || item === '>') {
                        switch (item) {
                            case '[': this.value = this.firstPage; break;
                            case '<': this.value = this.preview; break;
                            case '>': this.value = this.next; break;
                            case ']': this.value = this.lastPage; break;
                        }
                        _this.find(".paging-content").append(this._getPagingContentItemHtml(this._getType(item)));
                    }
                    if (item === 'g') {
                        _this.find(".paging-content").append(this._getPagingContentItemHtml(this._getType(item)));
                    }
                }
                _this.find(".paging-content").append("<div class='clean'></div>")
            }

            //获得分页控件内容元素的HTML
            this._getPagingContentItemHtml = function (type) {
                switch (type) {
                    case 'first':
                        if (this.currentPage <= this.firstPage) {
                            //disable
                            return '<li page = "' + this.value + '" class="page_dis width60"><a href="#">首页</a></li>';
                        } else {
                            return '<li page = "' + this.value + '" class="normal width60"><a href="#">首页</a></li>';
                        }

                    case 'preview':
                        if (this.value <= this.firstPage && this.value == this.currentPage) {
                            return '<li page = "' + this.value + '" class="page_dis width60"><a href="#">上一页</a></li>';
                        } else {
                            return '<li page = "' + this.value + '" class="normal width60"><a href="#">上一页</a></li>';
                        }
                    case 'block':
                        {
                            if (this.total <= 0) {
                                return;
                            }
                            if (this.value != this.currentPage) {
                                //normal
                                return '<li page = "' + this.value + '" class="normal width30" ><a href="#">' + this.value + '</a></li>';
                            } else {
                                //active
                                return '<li page = "' + this.value + '" class="page_now width30"><a href="#">' + this.value + '</a></li>';
                            }
                        }
                    case 'next':
                        if (this.value >= this.lastPage && this.value == this.currentPage) {
                            //disable
                            //console.log("value " + this.value + " lastPage " + this.lastPage + " diable");
                            return '<li page = "' + this.value + '" class="page_dis width60"><a href="#">下一页</a></li>';
                        } else {
                            //console.log("value " + this.value + " lastPage " + this.lastPage + " active");
                            return '<li page = "' + this.value + '" class="normal width60"><a href="#">下一页</a></li>';
                        }
                    case 'last':
                        if (this.currentPage >= this.lastPage) {
                            //disable
                            return '<li page = "' + this.value + '" class="page_dis width60"><a href="#">尾页</a></li>';
                        } else {
                            return '<li page = "' + this.value + '" class="normal width60"><a href="#">尾页</a></li>';
                        }
                    case 'goto':
                        if (this.lastPage <= 1) {
                            return '<li  class="page_dis width60 paging_goto"><a href="#" >跳转</a></li><li class="normal width60"><input type="text" class="normal width30 paging_pageIndex" disabled="disabled"/></li>';
                        } else {
                            return '<li  class="normal width60 paging_goto"><a href="#">跳转</a></li><li class="normal width60"><input type="text" class="normal width30 paging_pageIndex" /></li>';
                        }
                }
            }

            //显示分页框架提示信息
            this._showPagingMeaaage = function () {
                if (this.total <= 0) {
                    return;
                }
                _this.find(".paging-wapper").append('<p id="msg">共' + this.lastPage + '页' + this.total + '条记录</p>');
            }

            //注册时间
            this._regEvent = function () {
                var _paging = this;
                _this.find("[page]").each(function () {
                    $(this).click(function () {
                        _paging.go($(this).attr("page"));
                    });
                });
                //TODO : reg input box event and goto envent
                if (this.pattern.indexOf('g') >= -1) {
                    //页面输入处理
                    _this.find(".paging_pageIndex").keyup(function (event) {
                        var keycode = event.keyCode || event.which || event.charCode;

                        //enter
                        if (keycode === 13) {
                            return _paging.go($(this).val());
                        }


                        //如果是-> 或者 <- 等移动光标按键那么不做任何人处理
                        if (keycode > 36 && keycode < 41) {
                            return;
                        }

                        var value = $(this).val();
                        var result = "";
                        var len = value.length;


                        //过滤掉所有非数字字符
                        for (var i = 0; i < len && result.length < 4; i++) {
                            //首位字符不能为 0
                            if (i === 0) {
                                if (value.charAt(i) >= '1' && value.charAt(i) <= '9') {
                                    result += value.charAt(i);
                                }
                                continue;
                            }

                            if (value.charAt(i) >= '0' && value.charAt(i) <= '9') {
                                result += value.charAt(i);
                            }
                        }
                        $(this).val(result);
                    });

                    //注册跳转按钮跳转
                    _this.find(".paging_goto").click(function () {
                        _paging.go(_this.find(".paging_pageIndex").val());
                    })
                }
            }

            //验证页码是不是合法页码
            //返回合理的页码 
            this._vaildatePageIndex = function (pageIndex) {
                var reg = /^[1-9]|[0-9]{1,3}$/;

                //非法页面返回1
                if (!reg.test(pageIndex)) {
                    pageIndex = 1;
                } else {
                    pageIndex = pageIndex * 1;
                    if (pageIndex < this.firstPage || pageIndex > this.lastPage) {
                        pageIndex = 1;
                    }
                }
                return pageIndex;
            }
			
			this._vaildatePageIndexTemp = function (pageIndex) {
                var reg = /^[1-9]|[0-9]{1,3}$/;

                //非法页面返回1
                if (!reg.test(pageIndex)) {
                    pageIndex = 1;
                } else {
                    pageIndex = pageIndex * 1;
                }
                return pageIndex;
            }

            //触发分页事件
            this._triggerEvent = function () {
				//如果要求不触发分页事件那么就需要展示页面
				if(this.needTrigerEvent){
					$(this).trigger("paging");
				}else{
					this.show();
				}
				//触发外部回调事件
				this.pageChangeed(this.currentPage);
            }

            //清楚分页组件
            this._cleanPaging = function () {
                _this.html("");
            }
            /*--------------------------------------公共方法-----------------------------------*/
            //初始化 展示分页控件
            this.show = function () {
            	this._cleanPaging();
            	if (this.total <= 0) {
                    return;
                }
                this._showPagingFramework();
                this._showPagingMeaaage();
                this._showPagingContent();
                this._regEvent();
                return this;
            };


            //下一页
            this.next = function () {
                return this.go(this.currentPage + 1);
            };
            //上一页
            this.prev = function () {
                return this.go(this.currentPage - 1);
            };
            // go to  page 触发改变事件
            this.go = function (index) {
                this._setCurrentPage(index);
                this._triggerEvent();
                return this;
            };
            //重新设置分页控件
            this.refresh = function (option) {
                this._setOption(option);
                this._setTotal(option.total);
                this._setPageSize(option.pageSize);
                this._setPattern(option.pattern);
                this._setFirstPage();
                this._setLastPage();
                this._setCurrentPage(option.currentPage);
                this.option = undefined;
                this.show();
                delete this.option;
                return this;
            }
            return this._constructor(option);
        };

        _this.data(__dataKey, (_data = new Paging(option)));

        return _data;

    };

    $.fn.paging.option = {
        total: 0, // total element
        pageSize: 10, // number of elements per page
        currentPage: 1, // current page
        pattern: '[<ncnn>]g',
		needTrigerEvent : true
    }
} (jQuery));